export function setCookie(name, value, expires=undefined, path = "/") {
    if(expires == undefined){  // expires没有接收任何参数
        document.cookie = name + "=" + value + ";path="+ path;
    }else{
        var date = new Date();
        date.setSeconds(date.getSeconds() + expires); // 以秒为单位

        // 先编码  再存储
        document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + date.toUTCString() + ";path="+ path;
    }
}

/* function getCookie(name){ // 先将所有cookie解析为对象,在从对象中取值 
    var data = {}
    var cookie = document.cookie;
    if (cookie) {
        var list = cookie.split("; ");
        console.log(list);
        for (var i = 0; i < list.length; i++) {
            var item = list[i];
            var key = item.split("=")[0];
            var value = item.split("=")[1];
            data[key] = value;
        }
    }
    console.log(data);
    return data[name]||"";
} */

export function getCookie(name){ // 先将所有cookie解析为对象,在从对象中取值 
    var cookie = document.cookie;
    if (cookie) {
        var list = cookie.split("; ");
        for (var i = 0; i < list.length; i++) {
            var item = list[i];
            var key = item.split("=")[0];
            var value = item.split("=")[1];
            if(key === name){
                // 取值时 先解码在输出
                return decodeURIComponent(value);
            }
        }
    }
    return "";
}


export function deleteCookie(name){
    setCookie(name,"",-1);
}
